'use strict';

const {
	Controller
} = require('uni-cloud-router');
const {
	getUserInfo
} = require("user-info-admin");

const dbcmd = uniCloud.database().command;

module.exports = class GoodsController extends Controller {

	// 添加商品
	async add() {
		let response = {
			code: 1,
		};

		// 数据验证
		this.validate(this.ctx.data);

		let {
			goods
		} = this.ctx.data;
		let uniIdToken = this.ctx.event.uniIdToken
		let userInfo = await getUserInfo(uniIdToken)
		let app_id = userInfo.app_id
		
		goods.app_id=app_id
		goods.name = goods.name ? goods.name + '' : '';
		goods.name_pw = goods.name_pw ? goods.name_pw + '' : '';

		// 处理商品详情前端显示UI样式
		goods.desc_mobile = goods.desc_mobile.replace(/style="max-width:100%;"/gi, '').replace(/<img src/gi,
			'<img style="max-width:100%;display:block;" src');

		// 是否填写商品分享设置
		goods.share_title = goods.share_title ? goods.share_title + '' : goods.name;
		goods.share_img = goods.share_img || goods.img;
		goods.share_desc = goods.share_desc ? goods.share_desc + '' : goods.name_pw;

		// 商品默认值
		const goods_id = new Date().getTime() + (Math.round(Math.random() * 1000000) + '').padStart(6, '0');
		goods._id = goods_id;
		goods.stock_wh_num = goods.stock_num;
		goods.create_time = new Date().getTime();
		goods.create_uid = this.ctx.auth.uid;
		goods.create_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
		// 写入商品数据
		const goodsRes = await this.db.collection('wmzmall-integral-goods').add(goods);

		response.code = 0;
		response.msg = '提交成功';

		return response;
	}
	// 验证请求数据
	validate(req) {
		if (!req) this.throw('请求参数不存在');
		if (!req.goods) this.throw('商品参数不存在');

		if (!req.goods.name) this.throw('商品名称必填');
		if (!req.goods.cid) this.throw('请选择商品分类');
		if (req.goods.integral <= 0) this.throw('商城积分不能小于0');
		if (!req.goods.img) this.throw('请上传商品主图');
	}

	// 获取商品数据
	async detail() {
		let response = {
			code: 1,
			goods: {},
			goods_detail: {},
		};

		let start = new Date().getTime();
		const {
			goods_id
		} = this.ctx.data;

		// 产品数据
		let goods = await this.db.collection('wmzmall-integral-goods').doc(goods_id).get();

		if (!goods || goods.data.length <= 0) {
			response.msg = `当前产品不存在`;
			return response;
		}

		response.goods = goods.data[0];

		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 编辑商品
	async edit() {
		let response = {
			code: 1,
		};

		// 数据验证
		this.validate(this.ctx.data);

		let {
			goods_id,
			goods
		} = this.ctx.data;
		try {

			// 产品数据
			let __goods = await this.db.collection('wmzmall-integral-goods').doc(goods_id).get();

			if (!__goods || __goods.data.length <= 0) {
				response.msg = `当前产品不存在`;
				return response;
			}
			
			goods.name = goods.name ? goods.name + '' : '';
			goods.name_pw = goods.name_pw ? goods.name_pw + '' : '';

			// 处理商品详情前端显示UI样式
			goods.desc_mobile = goods.desc_mobile.replace(/style="max-width:100%;"/gi, '').replace(
				/<img src/gi, '<img style="max-width:100%;display:block;" src');

			// 是否填写商品分享设置
			goods.share_title = goods.share_title ? goods.share_title + '' : goods.name;
			goods.share_img = goods.share_img || goods.img;
			goods.share_desc = goods.share_desc ? goods.share_desc + '' : goods.name_pw;

			// 商品默认值
			goods.last_modify_uname = new Date().getTime();
			goods.last_modify_uid = this.ctx.auth.uid;
			goods.last_modify_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;

			delete goods._id;
			// 写入商品数据
			const goodsRes = await this.db.collection('wmzmall-integral-goods').doc(goods_id).set(goods);

			response.code = 0;
			response.msg = '提交成功';

		} catch (e) {
			//TODO handle the exception
			console.log('catch', e);
		}
		return response;
	}

	// 导入数据
	async import() {
		let response = {
			code: 1,
		};

		let {
			goodsDatas
		} = this.ctx.data;
		
		let uniIdToken = this.ctx.event.uniIdToken
		let userInfo = await getUserInfo(uniIdToken)
		let app_id = userInfo.app_id

		let ids = [];
		let addGoods = [];
		goodsDatas.forEach(x => {
			addGoods.push({
				cid: x.cid,
				cids: [x.cid],
				sort: x.sort,
				name: x.name,
				name_pw: x.name_pw,
				integral: x.price,
				price: x.market_price,
				limit: x.limit,
				stock_num: x.stock_num,
				exchange_cnt: 0,
				exchange: 0,
				visit_cnt: 0,
				visit: 0,
				collect_cnt: 0,
				collect: 0,
				share_cnt: 0,
				share: 0,
				sold_out_time: x.sold_out_time,
				state: '待审核',
				img: x.img,
				imgs: x.imgs,
				desc_mobile: x.desc_mobile,
				share_title: x.share_title,
				share_img: x.share_img,
				share_desc: x.share_desc,
				import_id: x._id,
				app_id:app_id,
				shop_id:x.shop_id
			})
			ids.push(x._id);
		});

		// todo 验证导入数据不能重复
		let exitsRes = await this.db.collection('wmzmall-integral-goods').where({
			import_id: this.db.command.in(ids)
		}).get();
		
		if (exitsRes.data && exitsRes.data.length > 0) {
			response.msg = '导入的商品数据已存在，请重新操作';
			return response;
		}

		// 写入商品数据
		const goodsRes = await this.db.collection('wmzmall-integral-goods').add(addGoods);

		response.code = 0;
		response.msg = '导入成功';
		response.datas = goodsRes;

		return response;
	}

	// 已收货
	//   结算分销订单（测试阶段，实际应为确认收货7天或15天禁止退换货之后结算）
	async orderReceived() {
		let response = {
			code: 1,
		};
		const start = new Date().getTime();
		const nowdate = start;

		const {
			order_id,
			state
		} = this.ctx.data;
		// console.log('this.ctx.data', this.ctx.data);
		const uid = this.ctx.auth.uid;

		let where_obj = {
			is_delete: 0,
			order_id: order_id
		};

		let orderRes = await this.db.collection('wmzmall-integral-order')
			.where(where_obj)
			.field({
				order_actural_paid: true,
				order_id: true,
				order_member_name: true,
				order_member_openid: true,
				order_member_headimg: true,
				order_info: true,
				order_goods_cnt: true,
				create_uid: true,
			})
			.get();

		if (!(orderRes && orderRes.data && orderRes.data.length == 1)) {
			uniCloud.logger.info(`订单[${order_id}]不存在`);
			response.msg = `订单[${order_id}]不存在`;
			return response;
		}
		const order = orderRes.data[0];

		let orderUpdate = {
			state: state,

			last_modify_time: nowdate,
			last_modify_uname: this.ctx.auth.userInfo.username,
			last_modify_uid: uid
		};

		const orderUpdateRes = await this.db.collection('wmzmall-integral-order')
			.doc(order._id)
			.update(orderUpdate);

		if (orderUpdateRes && orderUpdateRes.updated == 1) {
			const order_log = {
				order_id: order.order_id,
				log_type: '已收货',
				current_state: state,
				prev_state: '待收货',
				ip: this.ctx.context.CLIENTIP,
				is_delete: 0,
				create_uid: uid,
				create_uname: this.ctx.auth.userInfo.username,
				create_time: nowdate
			};
			await this.db.collection('wmzmall-order-log').add(order_log);
		}

		response.datas = orderUpdateRes;

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
}
